package com.wyp168.es.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import com.alibaba.fastjson.JSON;
import com.wyp168.common.to.es.SkuESModel;
import com.wyp168.es.config.ESConfig;
import com.wyp168.es.constants.ESConstants;
import com.wyp168.es.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName ProductSaveServiceImpl
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2023/8/13 13:09
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private ElasticsearchClient esClient;

    public static final String INDEX = "bank";

    @Override
    public Boolean productStatusUp(List<SkuESModel> esModelList) {
        try {
            //保存到es中
            //1.给es中建立索引。product，并且建立相应的映射关系
            //2.批量同步数据
            BulkRequest.Builder bulkRequestBuilder = new BulkRequest.Builder();
            for (SkuESModel model : esModelList) {
                bulkRequestBuilder.operations(op -> op
                        .index(idx -> idx
                                .index(ESConstants.PRODUCT_INDEX)
                                .id(model.getSkuId().toString())
                                .document(model)
                        )
                );
            }
            BulkResponse bulkResult = esClient.bulk(bulkRequestBuilder.build());
            if (bulkResult.errors()) {
                log.error("Bulk had errors");
                return false;
            } else {
                return true;
            }
        } catch (IOException e) {
            log.error("同步sku数据到es异常，e:{}", e.getMessage());
            return false;
        }
    }
}
